import {
	createRouter,
	createWebHashHistory
} from "vue-router"
import { defineAsyncComponent  } from 'vue';
import {getToken,removeToken} from "@/utils/cookie"
import store from "@/store/index"
import baseList from "./base.js"

export const router = createRouter({
	history: createWebHashHistory(),
	routes: [
		...baseList
	]
})
let tag = true
router.beforeEach(async (to, from, next) => {
	if(getToken()){
		if (tag) {
			tag = false
			//判断菜单数组中是否有数据
			var accessRoutes = [];
			if (store.state.menuList.length <= 0) {
				accessRoutes = await store.dispatch('generateRoutes')
			}else{
				accessRoutes = store.getters.getMenuList
			}
			if(accessRoutes.length>0){
				recursionMenu(accessRoutes) 
			}
			next(to.path)
		} else {
			next()
		}
	}else{
		  if (to.path == '/login') {//token不存在，并且是login页面
		   next();
		  } else {//token不存在，不是login页面
		   next('/login');
		  }
	}
	
	// if (tag) {
	// 	tag = false
	// 	//判断菜单数组中是否有数据
	// 	var accessRoutes = [];
	// 	if (store.state.menuList.length <= 0) {
	// 		accessRoutes = await store.dispatch('generateRoutes')
	// 	}else{
	// 		accessRoutes = store.getters.getMenuList
	// 	}
	// 	recursionMenu(accessRoutes) 
	// 	next(to.path)
	// } else {
		
	// 	next()
	// }
	//生成面包屑
	let cacheMatched = to.matched
	cacheMatched = cacheMatched.filter(item => item.meta && item.meta.title)
	store.commit("breadcrumbChange",cacheMatched)
	//生成打开栏页面数据
	if(cacheMatched[cacheMatched.length-1].meta.pname && cacheMatched[cacheMatched.length-1].meta.pname.length>0){
		store.commit("menuTagsChange",{
			'title':cacheMatched[cacheMatched.length-1].meta.title,
			'path':cacheMatched[cacheMatched.length-1].path,
			'select':true
		})
	}
	
})
//递归添加路由
function recursionMenu(e) {
	
	e.forEach(item => {
		if(item.meta.type == 1 || item.meta.show == 1){//如果为 按钮|不启用 则不继续执行
			return false
		}
		if (item.component == "#") {
			router.addRoute(item.meta.pname,{
				'path': (item.path == "#" ? '' : item.path),
				'component':loadView('layout/view'),
				'name' : (item.name == "#" ? '' : item.name),
				'meta': {
					'requiresAuth': true,
					'title': item.meta.title,
					'pname': item.meta.pname,
				}
			})
		}else{
			router.addRoute(item.meta.pname,{
				'path': (item.path == "#" ? '' : item.path),
				'component':loadView(item.component == '#' ? 'layout/view' : item.component),
				'name' : (item.name == "#" ? '' : item.name),
				'meta': {
					'requiresAuth': true,
					'title': item.meta.title,
					'pname': item.meta.pname,
				}
			})
		}

		if (item.children.length > 0) {
			recursionMenu(item.children)
		}
	})
}

export const loadView = (view) => {
	// return resolve => require([`/src/views/${item.component}.vue`], resolve)
	// 这里需要注意一下 vite+vue3 要用 defineAsyncComponent 才能拼接成功 不然会一直报错找不到模块
    return () => defineAsyncComponent(() => import(/* @vite-ignore */`/src/views/${view}.vue`))
}
